import { Toast, Dialog } from "vant"
import "file-saver";
import Vue from "vue";

export default class Download {
    static isSubmiting = false
    static download(item) {
            console.log(item)
                //路径下载
            if (item.filePath) {
                //新版i国网直接调用文件预览
                if (window.wx && navigator.appfilemanage && navigator.appfilemanage.openFile) {
                    // var deUrl = item.filePath;
                    var deUrl = item.url;
                    var u = Vue.prototype.$dealMsg('UPLOAD_URL').url
                        //http文件地址
                        // if (!deUrl.includes(u + "/sgitm")) {
                        //     deUrl = u + "/sgitm/app/oss" + (deUrl.match(/app\/oss(\S*)/) ? deUrl.match(/app\/oss(\S*)/)[1] : '')
                        // }
                    navigator.appfilemanage.openFile(deUrl, item.fileName)
                    return
                }
                Download.uploadUrl(item)
                return
            }
            //文件下载
            if (item.file) {
                item.fileName = item.fileName.replace(/#/g, ""); //包含#文件下载无法自动打开  
                Download.downloadFile(item.file, item.fileName)
                return
            }
            //base64下载
            if (item.base64) {
                Download.savebase64AsPDF(item);
                return
            }
        }
        //base64下载
    static savebase64AsPDF(item) {
            item.fileName = item.fileName.replace(/#/g, ""); //包含#文件下载无法自动打开 
            var block = item.base64.split(";");
            if (!block || block.length < 2) {
                Toast("该文件不支持下载！");
                return
            }
            var dataType = block[0].split(":")[1]; // In this case "application/pdf"
            // get the real base64 content of the file
            var realData = block[1].split(',')[1] // In this case "JVBERi0xLjcKCjE...."

            var filename = item.FILE_NAME;
            var DataBlob = Download.b64toBlob(realData, dataType);
            Download.downloadFile(DataBlob, filename)
        }
        //路径下载
    static uploadUrl(item) {
        var filename = item.fileName;
        var deUrl = item.url;
        Toast.loading({
            duration: 0,
            message: "下载中...",
            forbidClick: true
        });
        setTimeout(() => {
            Toast.clear();
        }, 10 * 1000);
        getBlob(deUrl, (blob) => {
            Download.downloadFile(blob, filename)
        });

        function getBlob(Url, cb) {
            console.log('getBlob', Url)
            var xhr = new XMLHttpRequest();
            xhr.open('GET', Url, true);
            xhr.responseType = 'blob';
            xhr.onload = function() {
                if (xhr.status === 200) {
                    cb(xhr.response);
                }
            };
            xhr.send();
        }
    }
    static b64toBlob(b64Data, contentType, sliceSize) {
        contentType = contentType || '';
        sliceSize = sliceSize || 512;

        var byteCharacters = atob(b64Data);
        var byteArrays = [];

        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);

            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            var byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

        var blob = new Blob(byteArrays, { type: contentType });
        return blob;
    }

    static downloadFile(blob, filename) {
            console.log('................下载')
            if (!window.resolveLocalFileSystemURL) {
                saveAs(blob, filename)
                Toast.clear();
                return
            }
            console.log('客户端下载')
            var u = navigator.userAgent;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
            console.log('isAndroid', isAndroid)
            var folderpath = '';
            if (isAndroid) {
                folderpath = 'file:///storage/emulated/0/'
            } else {
                folderpath = "file:///private/var/mobile/"
            }
            console.log('folderpath=' + folderpath)
            window.resolveLocalFileSystemURL(folderpath, function(dir) {
                console.log("Access to the directory granted succesfully dir=" + dir);
                dir.getFile(filename, { create: true }, function(file) {
                    console.log("File created succesfully.");
                    file.createWriter(function(fileWriter) {
                        Toast.clear();
                        //写入结束  
                        fileWriter.onwriteend = function() {
                            let finalPath = folderpath + filename
                                // Toast("下载文件成功！");
                            Dialog({
                                title: '下载成功！',
                                message: `文件存储地址为：${finalPath}`
                            });
                            console.log('isAndroid', isAndroid)
                            if (isAndroid) {
                                //文件路径格式
                                console.log("打开文件：" + finalPath);
                                navigator.appfilemanage.openFile(function(value) {
                                    //value 取值
                                    /**
                                     * 1 文件路径不存在
                                     -1 参数错误
                                    0 打开成功
                                    */
                                    console.log('打开成功回调 ：' + value);
                                }, function(msg) {
                                    console.log('打开失败回调：' + msg);
                                }, finalPath);
                            } else {
                                //open file
                                console.log("不是安卓：" + finalPath);
                                if (Download.getMimeTypes(filename)) {
                                    cordova.plugins && cordova.plugins.fileOpener2.open(finalPath, Download.getMimeTypes(filename));
                                }
                            }
                        }
                        fileWriter.onerror = function(e) {
                            Toast("下载文件失败！");
                            console.log('写入文件失败:' + e.toString());
                        }
                        fileWriter.write(blob);
                    }, function() {});
                });
            });
        }
        //获取文件 MIME-Types
    static getMimeTypes(fileName) {
        var nameList = fileName.split('.')
        var x = nameList[nameList.length - 1]
        var typesObj = {
            "doc": "application/msword",
            "pdf": "application/pdf",
            "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "png": "image/png",
            "jpg": "image/jpeg",
            "txt": "text/plain",
            "xls": "application/vnd.ms-excel",
            "ppt": "application/vnd.ms-powerpoint ",
            "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
            "zip": "application/zip",
            "": ""
        }
        return typesObj[x]
    }
    static blobtob64(blob, callback) {
        let oFileReader = new FileReader();
        oFileReader.onloadend = function(e) {
            let base64 = e.target.result;
            callback(base64)
        };
        oFileReader.readAsDataURL(blob);
    }

}